package lc20240504;

import java.util.*;

//49.字母异位词分组
public class Demo1 {

    public static void main(String[] args) {
        String[] strs={"eat","tea","tan","ate","nat","bat"};
        System.out.println("groupAnagrams(strs).toString() = " + groupAnagrams1(strs).toString());
    }
    public static List<List<String>> groupAnagrams(String[] strs) {
        if (strs==null||strs.length==0){
            return new ArrayList<>();
        }

        Map<String,List<String>> map=new HashMap<>();

        for (String s: strs) {
            char[] ch=s.toCharArray();
            Arrays.sort(ch);
            String sortedArray=Arrays.toString(ch);
            System.out.println(sortedArray);
            //如果不包含，说明是不同的字符串，需要新建List
            if (!map.containsKey(sortedArray)){
                map.put(sortedArray,new ArrayList<>());
            }
            map.get(sortedArray).add(s);
        }
        return new ArrayList<>(map.values()) ;
    }

    //第二种方法
    public static List<List<String>> groupAnagrams1(String[] strs) {
        if (strs == null || strs.length == 0) return new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();

        for (String s : strs) {
            // 初始化26位的计数器数组，每个字母对应一个位置
            int[] count = new int[26];
            // 计算每个字母的频率
            for (char c : s.toCharArray()) count[c - 'a']++;

            // 构建键字符串
            StringBuilder sb = new StringBuilder("");
            for (int i = 0; i < 26; i++) {
                sb.append('#');
                sb.append(count[i]);
            }
            String key = sb.toString();

            // 如果没有这个键，就创建
            if (!map.containsKey(key)) map.put(key, new ArrayList<>());
            map.get(key).add(s);
        }

        return new ArrayList<>(map.values());
    }

}
